package todo_app

type tTodoWriter struct {
}

func newTodoWriter() iTodoWriter {
	it := new(tTodoWriter)
	it.init()
	return it
}

func (me *tTodoWriter) init() {
	GlobalEventBus.Sub("todo.created", "", me.handleEvent)
}

func (me *tTodoWriter) handleEvent(e string, args interface{}) {
	switch e {
	case EventTodoCreated:
		if it, ok := args.(*TodoCreatedEvent); ok {
			me.HandleCreated(it)
		}
		break

	case EventTodoUpdated:
		if it, ok := args.(*TodoUpdatedEvent); ok {
			me.HandleUpdated(it)
		}
		break

	case EventTodoRemoved:
		if it, ok := args.(*TodoRemovedEvent); ok {
			me.HandleRemoved(it)
		}
		break
	}
}

func (me *tTodoWriter) HandleCreated(e *TodoCreatedEvent) {
	j := gDefaultEventSerializer.SerializeCreatedEvent(e)
	if j != nil {
		MockJSONStore.Append(j)
	}
}

func (me *tTodoWriter) HandleUpdated(e *TodoUpdatedEvent) {
	j := gDefaultEventSerializer.SerializeUpdatedEvent(e)
	if j != nil {
		MockJSONStore.Append(j)
	}
}

func (me *tTodoWriter) HandleRemoved(e *TodoRemovedEvent) {
	j := gDefaultEventSerializer.SerializeRemovedEvent(e)
	if j != nil {
		MockJSONStore.Append(j)
	}
}
